package vn.gq.udv.comic.model;

import java.io.IOException;
import java.util.LinkedList;
import java.util.zip.GZIPInputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import vn.gq.udv.comic.R;
import vn.gq.udv.comic.model.item.ChapterItem;
import vn.gq.udv.utils.IOUtils;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;


public class ChapterAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	private Handler mHandler;
	private Context context;
	private LinkedList<ChapterItem> data = new LinkedList<ChapterItem>();
	
	public ChapterAdapter(Context ctx) {
		context = ctx;
		mInflater = LayoutInflater.from(ctx);
		mHandler = new Handler();
	}
	
	public void load(final Runnable run) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					String json = IOUtils.convertStreamToString(new GZIPInputStream(context.getAssets().open("data/data")));
					JSONArray ob = (JSONArray) new JSONTokener(json).nextValue();
					for (int i=0;i<ob.length();i++) {
						JSONObject jsob = ob.getJSONObject(i);
						ChapterItem item = new ChapterItem(jsob);
						data.add(item);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				mHandler.post(run);
			}
		}).run();
	}
	
	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.item_list, parent, false);
			holder = new ViewHolder();
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.tvTitle = (TextView) convertView.findViewById(R.id.itemlist);
		ChapterItem item = (ChapterItem) getItem(position);
		holder.tvTitle.setText(item.getTitle());
		return convertView;
	}
	
	public class ViewHolder {
		public TextView tvTitle;
	}

}
